﻿#include "CPublicData.h"
#include <QFile>
#include <QDomDocument>
#include <QDebug>
#include <QCoreApplication>
#include <QLibrary>
#include <QDir>
#include <qthread.h>
bool CPublicData::initSql()
{
	if (m_pSqlDllOper == nullptr)
	{
		QString sConfigPath = QCoreApplication::applicationDirPath() + "/SmartControl.xml";
		// 获取当前程序路径
		QString exePath = QCoreApplication::applicationDirPath();
		// 构造 DLL 文件路径
		QString sDllPath = QDir(exePath).filePath("SqlOper.dll");
		m_pSqlDllOper = new CSqlDllOper(g_sTableName, sConfigPath, sDllPath);
	}
	return m_pSqlDllOper->initSql();
}

bool CPublicData::init()
{
	if (m_bInit)
	{
		return true;
	}
	if (!m_bConfig)
	{
		CPublicData::instance().getConfig();
		m_bConfig = true;
	}
	if (!m_bSqlInit)
	{
		CPublicData::instance().m_bSqlInit = CPublicData::instance().initSql();
		CPublicData::instance().m_pSqlDllOper->startWork();
		QThread::msleep(1000);
	}
	m_bInit = true;
	return m_bInit;
}

bool CPublicData::getConfig()
{
	QString sFilePath = QCoreApplication::applicationDirPath() + "/SmartControl.xml";
	QFile file(sFilePath);
	if (!file.open(QIODevice::ReadOnly))
	{
		qWarning() << "Failed to open config file:" << sFilePath;
		return false;
	}

	QDomDocument doc;
	if (!doc.setContent(&file))
	{
		qWarning() << "Failed to parse XML content.";
		file.close();
		return false;
	}
	file.close();

	QDomElement root = doc.documentElement();
	if (root.tagName() != "Robot")
	{
		qWarning() << "Invalid root element.";
		return false;
	}

	QDomElement mysqlElem = root.firstChildElement("MYSQL").firstChildElement("ConnectInfo");
	if (!mysqlElem.isNull())
	{
		QStringList parts = mysqlElem.attribute("ConnectInfo").split(";");
		if (parts.size() >= 5)
		{
			m_pConfig->dbName = parts[0];
			m_pConfig->dbPort = parts[1];
			m_pConfig->dbHost = parts[2];
			m_pConfig->dbUser = parts[3];
			m_pConfig->dbPassword = parts[4];
		}
	}
	QDomElement wsElem = root.firstChildElement("WEBSOCKET").firstChildElement("port");
	if (!wsElem.isNull())
	{
		m_pConfig->websocketPort = wsElem.attribute("port").toUShort();
	}
	QDomElement httpElem = root.firstChildElement("HTTPURL").firstChildElement("url");
	if (!httpElem.isNull())
	{
		m_pConfig->httpUrl = httpElem.attribute("url");
		m_sHttpUrl = m_pConfig->httpUrl;
	}
	m_bConfig = true;
	QDomElement pathElem = root.firstChildElement("PDFOUTPATH").firstChildElement("path");
	if (!pathElem.isNull())
	{
		m_sPdfOutputPath = pathElem.attribute("path");
	}
	QDomElement customElem = root.firstChildElement("CUSTOM").firstChildElement("name");
	if (!customElem.isNull())
	{
		m_sCustomName = customElem.attribute("name");
	}
	return true;
}

bool CPublicData::saveConfig()
{
	return true;
}


CPublicData::CPublicData()
{
	m_pConfig = new SmartControlConfig();
	m_bConfig = false;
	m_pSqlDllOper = nullptr;
	m_bSqlInit = false;
}

CPublicData::~CPublicData()
{
	if (m_pSqlDllOper != nullptr)
	{
		delete m_pSqlDllOper;
		m_pSqlDllOper = nullptr;
	}
}

